package com.maxuxu.scihome.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @className: DruidConfig
 * @cothor: Maxuxu
 * @date: 2022/6/29 22:15
 * @description: druid连接池的配置类
 */
@Configuration
public class DruidConfig {
    @Bean(name = "dataSource")
    @ConfigurationProperties("spring.datasource")
    @Primary
    public DruidDataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 配置Druid的监控，一个管理后台的Servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        //指定拦截器只拦截druid管理页面的请求
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单，如果没有设置或为空，则表示允许所有访问.（不能写成*，不然会报错）
        servletRegistrationBean.addInitParameter("allow", "");
        // IP黑名单(共同存在时，deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.19");
        //控制台管理的用户名和密码
        servletRegistrationBean.addInitParameter("loginUsername", "maxuxu");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置一个web监控的filter
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}